package com.phiture.erp.basic.core.service.impl;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.phiture.erp.basic.core.pojo.dto.ErpUserCustomizeConfigPageReqDTO;
import com.phiture.erp.basic.core.pojo.dto.ErpUserCustomizeConfigSaveReqDTO;
import com.phiture.erp.basic.core.service.ErpUserCustomizeConfigService;
import com.phiture.erp.basic.dal.entity.ErpUserCustomizeConfigDO;
import com.phiture.erp.basic.dal.mapper.ErpUserCustomizeConfigMapper;
import com.phiture.erp.common.enums.ErpCommonStatusEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.phiture.erp.common.constants.ErpUserCustomizeConfigKeyConstants.*;
import static com.phiture.erp.common.constants.ErrorCodeConstants.OPEN_AUTO_CREATE_PURCHASE_ORDER_FAIL;
import static com.phiture.erp.common.constants.ErrorCodeConstants.USER_CUSTOMIZE_CONFIG_NOT_EXISTS;

/**
 * 用户自定义配置 Service 实现类
 *
 * @author YH
 */
@Service
@RequiredArgsConstructor
public class ErpUserCustomizeConfigServiceImpl implements ErpUserCustomizeConfigService {
    private final ErpUserCustomizeConfigMapper userCustomizeConfigMapper;

    @Override
    public Long createUserCustomizeConfig(ErpUserCustomizeConfigSaveReqDTO createReqDTO) {
        // 插入
        ErpUserCustomizeConfigDO userCustomizeConfig = BeanUtils.toBean(createReqDTO, ErpUserCustomizeConfigDO.class);
        userCustomizeConfigMapper.insert(userCustomizeConfig);
        // 返回
        return userCustomizeConfig.getId();
    }

    @Override
    public void updateUserCustomizeConfig(ErpUserCustomizeConfigSaveReqDTO updateReqDTO) {
        // 校验存在
        validateUserCustomizeConfigExists(updateReqDTO.getId());
        // 更新
        ErpUserCustomizeConfigDO updateObj = BeanUtils.toBean(updateReqDTO, ErpUserCustomizeConfigDO.class);
        boolean isOpen = ErpCommonStatusEnum.isOpen(updateObj.getStatus());
        switch (updateObj.getConfigKey()) {
            case ERP_PRODUCTION_TASK_DEFAULT_APPROVED:
                // 生产任务审批配置逻辑处理
                updateObj.setConfigValue(isOpen ? "true" : "false");
                break;
            case ERP_PURCHASE_REQUEST_DEFAULT_APPROVED:
                // 采购申请单审批配置逻辑处理
                processPurchaseRequestDefaultApprovedConfig(updateObj, isOpen);
                break;
            case ERP_AUTO_CREATE_PURCHASE_ORDER:
                // 自动创建采购订单逻辑处理
                processAutoCreatePurchaseOrderConfig(updateObj, isOpen);
                break;
            default:
                break;
        }
        userCustomizeConfigMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long id) {
        ErpUserCustomizeConfigDO configDO = userCustomizeConfigMapper.selectById(id);
        if (configDO == null) {
            throw exception(USER_CUSTOMIZE_CONFIG_NOT_EXISTS);
        }

        String configKey = configDO.getConfigKey();
        Integer status = ErpCommonStatusEnum.convertStatus(configDO.getStatus());
        boolean isOpen = ErpCommonStatusEnum.isOpen(status);
        ErpUserCustomizeConfigDO updateConfig = new ErpUserCustomizeConfigDO();
        updateConfig.setId(id).setStatus(status);
        switch (configKey) {
            case ERP_PRODUCTION_TASK_DEFAULT_APPROVED:
                // 生产任务审批配置逻辑处理
                updateConfig.setConfigValue(isOpen ? "true" : "false");
                break;
            case ERP_PURCHASE_REQUEST_DEFAULT_APPROVED:
                // 采购申请单审批配置逻辑处理
                processPurchaseRequestDefaultApprovedConfig(updateConfig, isOpen);
                break;
            case ERP_AUTO_CREATE_PURCHASE_ORDER:
                // 自动创建采购订单逻辑处理
                processAutoCreatePurchaseOrderConfig(updateConfig, isOpen);
                break;
            default:
                break;
        }
        userCustomizeConfigMapper.updateById(updateConfig);
    }

    @Override
    public void deleteUserCustomizeConfig(Long id) {
        // 校验存在
        validateUserCustomizeConfigExists(id);
        // 删除
        userCustomizeConfigMapper.deleteById(id);
    }

    private void validateUserCustomizeConfigExists(Long id) {
        if (userCustomizeConfigMapper.selectById(id) == null) {
            throw exception(USER_CUSTOMIZE_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public ErpUserCustomizeConfigDO getUserCustomizeConfig(Long id) {
        return userCustomizeConfigMapper.selectById(id);
    }

    @Override
    public PageResult<ErpUserCustomizeConfigDO> getUserCustomizeConfigPage(ErpUserCustomizeConfigPageReqDTO pageReqDTO) {
        return userCustomizeConfigMapper.selectPage(pageReqDTO, new LambdaQueryWrapperX<ErpUserCustomizeConfigDO>()
                .eqIfPresent(ErpUserCustomizeConfigDO::getStatus, pageReqDTO.getStatus())
                .likeIfPresent(ErpUserCustomizeConfigDO::getConfigKey, pageReqDTO.getConfigKey())
                .eqIfPresent(ErpUserCustomizeConfigDO::getConfigValue, pageReqDTO.getConfigValue())
                .betweenIfPresent(ErpUserCustomizeConfigDO::getCreateTime, pageReqDTO.getCreateTime())
                .orderByDesc(ErpUserCustomizeConfigDO::getId));
    }

    @Override
    public ErpUserCustomizeConfigDO getUserCustomizeConfig(String configKey) {
        return userCustomizeConfigMapper.selectOne(ErpUserCustomizeConfigDO::getConfigKey, configKey);
    }

    @Override
    public List<ErpUserCustomizeConfigDO> getUserCustomizeConfigList(Collection<String> configKeys) {
        return userCustomizeConfigMapper.selectList(ErpUserCustomizeConfigDO::getConfigKey, configKeys);
    }

    private void processPurchaseRequestDefaultApprovedConfig(ErpUserCustomizeConfigDO updateConfig, boolean isOpen) {
        updateConfig.setConfigValue(isOpen ? "true" : "false");
        // 同时关闭"erp_auto_create_purchase_order"的配置
        if (!isOpen) {
            userCustomizeConfigMapper.update(
                    Wrappers.lambdaUpdate(ErpUserCustomizeConfigDO.class)
                            .set(ErpUserCustomizeConfigDO::getStatus, ErpCommonStatusEnum.CLOSE.getStatus())
                            .set(ErpUserCustomizeConfigDO::getConfigValue, "false")
                            .eq(ErpUserCustomizeConfigDO::getDeleted, Boolean.FALSE)
                            .eq(ErpUserCustomizeConfigDO::getConfigKey, ERP_AUTO_CREATE_PURCHASE_ORDER)
            );
        }
    }

    private void processAutoCreatePurchaseOrderConfig(ErpUserCustomizeConfigDO updateConfig, boolean isOpen) {
        updateConfig.setConfigValue(isOpen ? "true" : "false");
        // 开启前判断"erp_purchase_request_default_approved"生态，只有开启状态才允许该配置开启
        if (isOpen) {
            ErpUserCustomizeConfigDO purchaseRequestConfig = userCustomizeConfigMapper.selectOne(ErpUserCustomizeConfigDO::getConfigKey, ERP_PURCHASE_REQUEST_DEFAULT_APPROVED);
            Assert.notNull(purchaseRequestConfig, "erp_purchase_request_default_approved 配置不能为空");
            if (ErpCommonStatusEnum.isClose(purchaseRequestConfig.getStatus())) {
                throw exception(OPEN_AUTO_CREATE_PURCHASE_ORDER_FAIL);
            }
        }
    }

}